package com.foftact.stockpereport.controller;

import com.foftact.stockpereport.StockPEReport;
import com.foftact.stockpereport.service.StockPEReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 股票财务分析报告控制器
 */
@Controller
@RequestMapping("/stockpereport")
public class StockPEReportController {

    private static final Logger logger = LoggerFactory.getLogger(StockPEReportController.class);

    @Autowired
    private StockPEReportService stockPEReportService;

    /**
     * 跳转到股票财务分析报告首页
     */
    @RequestMapping("/index")
    public String index(Model model) {
        // 获取所有股票财务分析报告数据
        List<StockPEReport> reports = stockPEReportService.getAllStockPEReports();
        model.addAttribute("reports", reports);
        return "stockpereport/index";
    }

    /**
     * 抓取并保存股票财务分析报告数据
     */
    @RequestMapping("/fetch")
    @ResponseBody
    public Map<String, Object> fetchData() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("开始抓取股票财务分析报告数据");
            int count = stockPEReportService.fetchAndSaveStockPEReportData();
            result.put("success", true);
            result.put("message", "数据抓取成功，共处理 " + count + " 条记录");
            result.put("count", count);
        } catch (Exception e) {
            logger.error("数据抓取失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "数据抓取失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 处理近20个季度数据
     */
    @RequestMapping("/process20Quarters")
    @ResponseBody
    public Map<String, Object> process20Quarters(@RequestParam String securityCode, 
                                               @RequestParam String securityName) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("开始处理股票 {} 近20个季度数据", securityCode);
            int count = stockPEReportService.process20QuartersData(securityCode, securityName);
            result.put("success", true);
            result.put("message", "季度数据处理成功，共处理 " + count + " 条记录");
            result.put("count", count);
        } catch (Exception e) {
            logger.error("季度数据处理失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "季度数据处理失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据股票代码查询股票财务分析报告
     */
    @RequestMapping("/getByCode")
    @ResponseBody
    public Map<String, Object> getByCode(@RequestParam String securityCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            StockPEReport report = stockPEReportService.getStockPEReportBySecurityCode(securityCode);
            result.put("success", true);
            result.put("data", report);
        } catch (Exception e) {
            logger.error("查询股票财务分析报告失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取近20个季度的报告数据
     */
    @RequestMapping("/getRecent20Quarters")
    @ResponseBody
    public Map<String, Object> getRecent20Quarters(@RequestParam String securityCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<StockPEReport> reports = stockPEReportService.getRecent20QuartersByCode(securityCode);
            result.put("success", true);
            result.put("data", reports);
        } catch (Exception e) {
            logger.error("查询近20个季度报告数据失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除旧数据
     */
    @RequestMapping("/deleteOldData")
    @ResponseBody
    public Map<String, Object> deleteOldData(@RequestParam(defaultValue = "90") int days) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = stockPEReportService.deleteOldData(days);
            result.put("success", true);
            result.put("message", "旧数据删除成功，共删除 " + count + " 条记录");
            result.put("count", count);
        } catch (Exception e) {
            logger.error("删除旧数据失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 查看单个股票的详细信息
     */
    @RequestMapping("/detail/{securityCode}")
    public String detail(@PathVariable String securityCode, Model model) {
        try {
            // 获取股票的财务分析报告
            StockPEReport report = stockPEReportService.getStockPEReportBySecurityCode(securityCode);
            model.addAttribute("report", report);
            
            // 获取近20个季度的数据
            List<StockPEReport> quarterlyReports = stockPEReportService.getRecent20QuartersByCode(securityCode);
            model.addAttribute("quarterlyReports", quarterlyReports);
            
        } catch (Exception e) {
            logger.error("查询股票详情失败: {}", e.getMessage(), e);
            model.addAttribute("error", "查询失败: " + e.getMessage());
        }
        return "stockpereport/detail";
    }

    /**
     * 提供REST API接口：获取所有股票财务分析报告
     */
    @RequestMapping("/api/reports")
    @ResponseBody
    public Map<String, Object> apiGetAllReports() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<StockPEReport> reports = stockPEReportService.getAllStockPEReports();
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", reports);
        } catch (Exception e) {
            logger.error("API查询失败: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 提供REST API接口：根据股票代码获取财务分析报告
     */
    @RequestMapping("/api/reports/{securityCode}")
    @ResponseBody
    public Map<String, Object> apiGetReportByCode(@PathVariable String securityCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            StockPEReport report = stockPEReportService.getStockPEReportBySecurityCode(securityCode);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", report);
        } catch (Exception e) {
            logger.error("API查询失败: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 提供REST API接口：根据股票代码获取近20个季度的数据
     */
    @RequestMapping("/api/reports/{securityCode}/quarters")
    @ResponseBody
    public Map<String, Object> apiGetQuarterlyReports(@PathVariable String securityCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<StockPEReport> reports = stockPEReportService.getRecent20QuartersByCode(securityCode);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", reports);
        } catch (Exception e) {
            logger.error("API查询失败: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }
}